package com.tanhua.manager.utils;

import com.tanhua.manager.domain.Admin;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtils {
    /**
     * 生成token
     */
    public static String createToken(Admin admin, String signature) {
        return Jwts.builder()
                .claim("id", admin.getId())
                .claim("username", admin.getUsername())
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
    }

    /**
     * 验证token是否合法
     */
    public static boolean isValidToken(String token, String signature) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析token
     */
    public static Admin parseToken(String token, String signature) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        Admin admin = new Admin();
        Object id = claimsJws.getBody().get("id");
        String username = (String) claimsJws.getBody().get("username");

        admin.setId(Long.parseLong(String.valueOf(id)));
        admin.setUsername(username);
        return admin;
    }
}
